package com.mall.consumer;

import com.mall.pojo.goods.TransactionLog;
import com.mall.pojo.order.Order;
import com.mall.pojo.order.OrderItem;
import com.mall.service.goods.SkuService;
import com.mall.service.order.TransactionLogService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.messaging.Message;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

@RocketMQTransactionListener(txProducerGroup = "tx_order")
public class TransactionListenerImpl implements RocketMQLocalTransactionListener {

    @DubboReference
    private SkuService skuService;

    @DubboReference
    private TransactionLogService transactionLogService;

    private AtomicInteger transactionIndex = new AtomicInteger(0);

    private ConcurrentHashMap<String, Integer> localTrans = new ConcurrentHashMap<>();


    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object param) {
        String transId = (String) message.getHeaders().get(RocketMQHeaders.PREFIX + RocketMQHeaders.TRANSACTION_ID);
        try {
            Map map=(Map)param;
            Order order = (Order) map.get("order");
            CountDownLatch latch = (CountDownLatch) map.get("latch");
            List<OrderItem> orderItemList = (List<OrderItem>)order.getOrderItemList();
            skuService.deductionStock(orderItemList,transId);
            latch.countDown();
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            return RocketMQLocalTransactionState.UNKNOWN;
        }

    }

    /**
     * 如果订单入库成功了那么需要讲半消息投递出去
     * @param msg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        String transId = (String) msg.getHeaders().get(RocketMQHeaders.PREFIX + RocketMQHeaders.TRANSACTION_ID);
        TransactionLog transactionLog = transactionLogService.getByTransId(transId);
        if (transactionLog!=null){
            return RocketMQLocalTransactionState.COMMIT;
        }else {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }


}
